package com.angle.im.server.config.mq.listeners;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.angle.im.server.config.mq.domain.SendToListMqBody;
import com.angle.im.server.domain.ImServer;
import com.angle.im.server.service.ServerService;
import com.angle.im.server.service.SocketServer;
import com.angle.im.server.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhangwei
 * @date 2019/4/15 17:49
 * @desc 点对点消息监听
 */
@Component
public class SendListListener implements MessageListener {


    @Autowired
    private ServerService serverService;
    @Autowired
    private SocketServer socketServer;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        SendToListMqBody sendToOneMqBody = CommonUtils.byteArrToObj(message.getBody(), SendToListMqBody.class);
        String platform = sendToOneMqBody.getPlatform();
        List<String> toList = sendToOneMqBody.getToList();
        toList.forEach(to -> {
            String serverId = serverService.getServerIdByUserId(platform, to);
            //这里选择全部遍历,并且不跳出的原因是   牺牲系统性能来减少mq的发送数量
            if (StringUtils.isNotBlank(serverId) || serverId.equals(ImServer.INSTANCE.LOCAL_SERVER_ID)) {
                socketServer.sendToOne(sendToOneMqBody.getFrom(), to, sendToOneMqBody.getMsg());
            }
        });
        return Action.CommitMessage;
    }
}
